import 'dart:convert';

import 'package:dio/dio.dart';

class ChatStreamService {
  static final Dio _dio = Dio()
    ..options.connectTimeout = const Duration(seconds: 500)
    ..options.sendTimeout = const Duration(seconds: 500)
    // ..options.receiveTimeout =const Duration(seconds: 500)
    ..options.receiveTimeout =
        null // 关键：流式请求不要设置接收超时
    ..options.contentType = 'application/json';


  int debugCount = 0;

  Stream<String> chatStream(Map<String, dynamic> body) async* {
    print('--------------ChatStreamHandlerV2--- $body');
    try {
      final response = await _dio.post<ResponseBody>(
        'https://fc.hongfund.com:8503/chat',
        data: body,
        options: Options(responseType: ResponseType.stream),
      );
      final responseBody = response.data!;
      StringBuffer buffer = StringBuffer();
      await for (final data in responseBody.stream) {
        // debugCount ++;
        // print('--------------ChatStreamHandlerV2--- debugCount :$debugCount $data');

        try {
          final content = utf8.decode(data);
          buffer.write(content);

          // 处理 SSE 格式 (data: ...\n\n)
          String bufferStr = buffer.toString();
          List<String> lines = bufferStr.split('\n\n');

          // 处理完整的事件
          for (int i = 0; i < lines.length - 1; i++) {
            String line = lines[i].trim();
            if (line.startsWith('data: ')) {
              String eventData = line.substring(6); // 移除 "data: " 前缀
              yield eventData;
            } else if (line.startsWith('data:')) {
              String eventData = line.substring(5).trim(); // 移除 "data:" 前缀
              yield eventData;
            }
          }
          // 保留最后一个可能不完整的事件
          buffer = StringBuffer(lines.last);
        } catch (e) {
          print('Decode error: $e');
          yield 'Decode error: $e';
        }
      }

      // 处理缓冲区中剩余的数据
      if (buffer.isNotEmpty) {
        String remaining = buffer.toString().trim();
        if (remaining.startsWith('data: ')) {
          String eventData = remaining.substring(6);
          yield eventData;
        } else if (remaining.startsWith('data:')) {
          String eventData = remaining.substring(5).trim();
          yield eventData;
        } else if (remaining.isNotEmpty) {
          yield remaining;
        }
      }
    } on DioException catch (e) {
      yield "DioException: ${e.message}";
    } catch (e) {
      yield "Exception: $e";
    }
  }
}
